package com.qf.commons.event.mq.rabbitmq.handler;

import com.qf.commons.event.entity.QphoneMessage;
import com.qf.commons.event.mq.rabbitmq.commons.Constacts;
import com.qf.commons.event.mq.standrad.MqProduceStandard;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * RabbitMq发送消息的核心实现
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Slf4j
public class RabbitMQProduceStandardHandler implements MqProduceStandard {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMessage(QphoneMessage qphoneMessage) {
        log.info("[send msg] - 事件总线发送消息，基于RabbitMQ - {}", qphoneMessage);

        //将自定义的消息对象进行序列化
        byte[] bytes = SerializationUtils.serialize(qphoneMessage);

        //设置消息的一些属性
        MessageProperties messageProperties = new MessageProperties();
        //设置消息的持久化
        messageProperties.setDeliveryMode(qphoneMessage.getMsgType() == 0 ? MessageDeliveryMode.NON_PERSISTENT : MessageDeliveryMode.PERSISTENT);

        //判断当前消息是否延迟
        long delayMs = qphoneMessage.getDelayMs();
        if (delayMs > 0) {
            //设置延迟时间
            messageProperties.setHeader("x-delay", delayMs);
        }

        //再创建一个RabbitMQ封装的Message对象中
        Message message = new Message(bytes, messageProperties);

        //封装CorrelationData对象 - 消息确认机制时 会返回当前消息
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(qphoneMessage.getMsgId());
        correlationData.setReturnedMessage(message);

        //发送消息
        if (delayMs > 0) {
            rabbitTemplate.send(Constacts.DELAY_EXCHANGE_NAME, qphoneMessage.getEventType(), message, correlationData);
        } else {
            rabbitTemplate.send(Constacts.EVENT_EXCHANGE_NAME, qphoneMessage.getEventType(), message, correlationData);
        }
    }
}
